<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>YUI Browser History Manager - Simple Navigation Bar (YUI Library)</title>
    <link type="text/css" rel="stylesheet" href="../../../build/reset-fonts-grids/reset-fonts-grids.css"/>
    <link rel="stylesheet" type="text/css" href="../../../examples/assets/dpSyntaxHighlighter.css"/>
    <link type="text/css" rel="stylesheet" href="../assets/tutorial.css"/>
  </head>
  <body>
    <div id="doc3" class="yui-t4">
      <div id="hd">
        <a href="http://developer.yahoo.com/yui" id="logo"><div></div></a>
        <h1>YUI Browser History Manager: Simple Navigation Bar</h1>
      </div>
      <div id="bd">
        <div id="toc" class="yui-b">
          <ul>
            <li class="sect"><a href="../index.html">YUI Browser History Manager: Tutorials</a></li>
            <li class="item selected"><a href="index.html">Simple Navigation Bar</a></li>
            <li class="child active"><a href="index.html">Tutorial</a></li>
            <li class="child"><a href="solution/index.html">Functional Example</a></li>
            <li class="item"><a href="../tabview/index.html">TabView Control</a></li>
            <li class="item"><a href="../calendar/index.html">Calendar Control</a></li>
            <li class="item"><a href="../multi/index.html">Multiple Modules</a></li>
          </ul>
        </div>
        <div id="yui-main">
          <div class="yui-b">

            <p>This example demonstrates how to use the Browser History Manager to "ajaxify" a simple navigation bar.</p>

            <h2 class="first">Basic Markup</h2>

<textarea name="code" class="HTML" cols="60" rows="1">
<html>
  <body>
    <div id="nav">
      <ul>
        <li><a href="?section=home">Home</a></li>
        <li><a href="?section=overview">Overview</a></li>
        <li><a href="?section=products">Products</a></li>
        <li><a href="?section=contactus">Contact Us</a></li>
      </ul>
    </div>
    <div id="bd">
&lt;?php

$section = "home";
if ( isset( $_GET["section"] ) )
    $section = $_GET["section"];
include( "./inc/" . $section . ".php" );

?&gt;
    </div>
  </body>
</html>
</textarea>

            <p>
              The small portion of PHP code is responsible for including the content
              specified by the "section" parameter in the URL. This technique avoids
              having to rewrite common parts of a web site such as header and footer.
            </p>

            <p>
              This page is already fully functional. However, clicking on the links
              in the navigation bar will refresh the entire page, including portions
              that are common to all the sections. This is highly inefficient (especially
              for a large web site), and using AJAX will allow us to optimize this.
              The idea is to use client-side scripting to intercept the click event,
              cancel it, and use the YUI Connection Manager to asynchronously load the
              content of the section, which we can then write to the document using
              innerHTML. The only downside of this approach is that it breaks the back/forward
              buttons, and individual sections cannot be bookmarked anymore. The Browser
              History Manager will help us work around this issue.
            </p>

            <h2>Import the source files and dependencies</h2>

            <p>
              In our example, we need the Connection Manager, Event Utility,
              DOM Utility, and the Browser History Manager:
            </p>

<textarea name="code" class="HTML" cols="60" rows="1">
<script src="yahoo.js"></script>
<script src="connection.js"></script>
<script src="event.js"></script>
<script src="dom.js"></script>
<script src="history-experimental.js"></script>
</textarea>

            <h2>Write the code necessary to load a section of the web site</h2>

            <p>
              Use the YUI Connection Manager's <code>asyncRequest</code> to achieve this:
            </p>

<textarea name="code" class="JScript" cols="60" rows="1">
function loadSection( section ) {
    var url = "./inc/" + section + ".php";

    function successHandler( obj ) {
        // Use the response...
        YAHOO.util.Dom.get( "bd" ).innerHTML = obj.responseText;
    }

    function failureHandler( obj ) {
        // Fallback...
        location.href = "?section=" + section;
    }

    YAHOO.util.Connect.asyncRequest( "GET", url,
        {
            success:successHandler,
            failure:failureHandler
        }
    );
}
</textarea>

            <h2>Design your application</h2>

            <p>
              In our simple example, we have only one module, represented by the
              navigation bar. We will refer to this module using the identifier
              "navbar". The state of the navigation module will be represented
              using the name of the corresponding section ("home", "overview",
              "products", etc.)
            </p>

            <h2>Retrieve the initial state of the navigation module</h2>

            <p>
              Use the <code>YAHOO.util.History.getBookmarkedState</code> method to find out
              the initial state of a module according to the URL fragment identifier
              (which is present if the user had previously bookmarked the application).
              In our example, we also use the <code>YAHOO.util.History.getQueryStringParameter</code>
              method to find out the initial state of a module according to the query string
              (which is present if the user reached the page using a search engine, or if
              the user did not have scripting enabled when previously bookmarking the page).
              Finally, default to "home":
            </p>

<textarea name="code" class="JScript" cols="60" rows="1">
var bookmarkedSection = YAHOO.util.History.getBookmarkedState( "navbar" );
var querySection = YAHOO.util.History.getQueryStringParameter( "section" );
var initialSection = bookmarkedSection || querySection || "home";
</textarea>

            <h2>Register the navigation module</h2>

            <p>
              Use the <code>YAHOO.util.History.register</code> method, passing in
              the navigation module identifier, the initial state of the navigation
              module, and the callback function that will be called when the
              state of the navigation module has changed:
            </p>

<textarea name="code" class="JScript" cols="60" rows="1">
YAHOO.util.History.register( "navbar", initialSection, function( state ) {
    // Load the appropriate section:
    loadSection( state );
} );
</textarea>

            <h2>Write the code that initializes your application</h2>

            <p>
              First of all, we want to change the behavior of the links in the navigation bar.
              In order to do this, we simply enumerate them, and attach to each individual anchor
              an <code>onclick</code> handler. In the <code>onclick</code> handler, we cancel
              the event's default behavior and do some custom action.
            </p>

            <p>
              We also need to display the default section if a section was requested via the URL
              fragment identifier, and that section is different from the one loaded using PHP:
            </p>

<textarea name="code" class="JScript" cols="60" rows="1">
function initializeNavigationBar() {
    // Process links
    var anchors = YAHOO.util.Dom.get( "nav" ).getElementsByTagName( "a" );
    for ( var i=0, len=anchors.length ; i<len ; i++ ) {
        var anchor = anchors[i];
        YAHOO.util.Event.addListener( anchor, "click", function( evt ) {
            var href = this.getAttribute( "href" );
            var section = YAHOO.util.History.getQueryStringParameter( "section", href ) || "home";
            // If the Browser History Manager was not successfuly initialized,
            // the following call to YAHOO.util.History.navigate will throw an
            // exception. We need to catch it and update the UI. The only
            // problem is that this new state will not be added to the browser
            // history.
            //
            // Another solution is to make sure this is an A-grade browser.
            // In that case, under normal circumstances, no exception should
            // be thrown here.
            try {
                YAHOO.util.History.navigate( "app", section );
            } catch ( e ) {
                loadSection( section );
            }
            YAHOO.util.Event.preventDefault( evt );
        } );
    }

    // This is the tricky part... The onLoad event is fired when the user
    // comes back to your page using the back button. In this case, the
    // actual section that needs to be loaded corresponds to the last section
    // visited before leaving the page, and not the initial section. This can
    // be retrieved using getCurrentState:
    var currentSection = YAHOO.util.History.getCurrentState( "app" );
    if ( location.hash.substr(1).length > 0 ) {
        // If the section requested in the URL fragment is different from
        // the section loaded in index.php, we have an unpleasant refresh
        // effect because we do an asynchronous XHR call. Instead of doing
        // a synchronous XHR call, we can fix this by erasing the initial
        // content of bd:
        if ( currentSection != querySection )
            YAHOO.util.Dom.get( "bd" ).innerHTML = "";
        loadSection( currentSection );
    }
}
</textarea>

            <h2>Subscribe to the Browser History Manager <code>onLoad</code> event</h2>

<textarea name="code" class="JScript" cols="60" rows="1">
YAHOO.util.History.onLoadEvent.subscribe( function() {
    initializeNavigationBar();
} );
</textarea>

            <h2>Initialize the Browser History Manager</h2>

            <p>
              Simply call <code>YAHOO.util.History.initialize</code> from a script
              block located right after the opening body tag:
            </p>

<textarea name="code" class="JScript" cols="60" rows="1">
try {
    YAHOO.util.History.initialize();
} catch ( e ) {
    initializeNavigationBar();
}
</textarea>

            <p>
              In our example, we wrapped the call to <code>YAHOO.util.History.initialize</code>
              by a <code>try...catch</code> block. Indeed, this method may throw an exception
              if the browser is not an A-grade browser. You may want to catch the exception
              and do something, or test which browser you're on before calling this method.
            </p>

            <div id="stepnav">
              <a class="next" href="solution/index.html">Continue to <em>Functional Example</em> &gt;</a>
            </div>

          </div>
        </div>
      </div>
      <div id="ft">&nbsp;</div>
    </div>
    <script src="../../../examples/assets/dpSyntaxHighlighter.js"></script>
    <script language="javascript">
      dp.SyntaxHighlighter.HighlightAll('code');
    </script>
  </body>
</html>
